import Vue from 'vue';
import utils from '../utils/utils.js'

let silentLoginInst = null
let getSilentLoginInst = (res) => {
	if (silentLoginInst) {
		return silentLoginInst
	}
	silentLoginInst = new Promise(async (resolve, reject) => {
		await wxLogin(resolve, reject)
	})
	return silentLoginInst
}
// 获取小程序配置
const getAppletConfig = async (params) => {
	let res = await Vue.prototype.$request({
		url: 'api/miniApp/index/config',
		method: 'GET',
		data:params
		// {
		// 	tag_id: 'tag2',
		// }
	},false)
	let config = {};
	for (const key in res.data.theme) {
		if (Object.hasOwnProperty.call(res.data.theme, key)) {
			const element = res.data.theme[key];
			config[key] = {};
			for (const key2 in element) {
				if (Object.hasOwnProperty.call(element, key2)) {
					const element2 = element[key2];
					config[key][key2] = element2?.val
				}
			}
		}
	}
	console.log('config', config);
	Vue.prototype.$store.dispatch('gConfig/_setAppletConfig', config);

};
let wxLogin = (resolve, reject) => {
	uni.login({
		success: async (loginRes) => {
			let { code, data, msg } = await Vue.prototype.$request({
				//url: 'api/miniApp/openid',
				url: 'api/miniApp/passport/login',
				method: 'POST',
				data: { code: loginRes.code,from_channel:Vue.prototype.$store.getters['user/channelGetters'] },
			})
			let { user_name, access_token } = data;
			uni.setStorageSync('openid', user_name);
			uni.setStorageSync('_access_token', access_token);
			if(code == 0){
				setTimeout(() => {
					getAppletConfig();
					getCrmUserInfo();
				}, 1000);
			}
			resolve({ code, data, msg })
		},
		fail: () => {
			reject()
		},
	})
}

let silentLogin = () => {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		// let openid = uni.getStorageInfoSync('openid')
		uni.checkSession({
			success: (result) => {
				// if (openid) {
				// 	resolve(openid)
				// } else {
				getSilentLoginInst().then(e => {
					resolve(e)
				})
				// }
			},
			fail: (error) => {
				getSilentLoginInst().then(e => {
					resolve(e)
				})
			}
		})
		// #endif
		// #ifdef H5
		// 20230114 adam说客户不需要h5授权openid 1111兼容接口
		let params = '111111111111111111' //utils.getUrlParam('openid') || uni.getStorageSync('openid');
		uni.setStorageSync('openid', params)
		if (!params) {
			Vue.prototype.$request({
				url: 'api/miniApp/openid',
				method: 'GET',
				data: {
					url: `${encodeURIComponent(window.location.href)}`
				}
			}).then(res => {
				window.location.href = res.result
			});
		} else {
			resolve()
		}
		// #endif
	})
}

let clearSilentLoginInst = () => {
	silentLoginInst = null;
}

const getCrmUserInfo = async () => {
	Vue.prototype.$store.dispatch('user/getUserInfo');
}
export default {
	silentLogin,
	clearSilentLoginInst,
	getAppletConfig
}
